IF OBJECT_ID('dbo.RptSubContractOutActivityDetailReport') IS NOT NULL
BEGIN
    DROP PROCEDURE dbo.RptSubContractOutActivityDetailReport
    IF OBJECT_ID('dbo.RptSubContractOutActivityDetailReport') IS NOT NULL
        PRINT '<<< FAILED DROPPING PROCEDURE dbo.RptSubContractOutActivityDetailReport >>>'
    ELSE
        PRINT '<<< DROPPED PROCEDURE dbo.RptSubContractOutActivityDetailReport >>>'
END
go
-- =======================================================================
-- Procedure Name: dbo.RptSubContractOutActivityDetailReport
--
-- Author:      Kevin Cashman, Parallax Consulting LLC
--
-- Create date: 10/06/2008
--
-- Description: Gets Raw data of SubDeliverables Out Activity
--
-- Serves as a drill down to the Report, RptSubContractOutActivityReport
--
-- Parameters:  
--     @StartDate                         
--     @EndDate                           
--     @DeliverableStatus                 
--     @Institution                       
--     @Department                        
--     @Unit                              
--     @Subcontractor                     
--     @SubcontractSpecialist             
--     @DomainUserId                      
--
--
-- Returns:     INT, 0=Success, -1=Error
--
-- SampleCall:
-- EXECUTE dbo.RptSubContractOutActivityDetailReport(
--                       @StartDate               = '6/1/2008',
--                       @EndDate                 = '8/31/2008',
--                       @DeliverableStatus       = NULL, 
--                       @Institution             = NULL, 
--                       @Department              = NULL, 
--                       @Unit                    = NULL, 
--                       @Subcontractor           = NULL, 
--                       @SubcontractSpecialist   = NULL, 
--                       @DomainUserId            = 11055 )
--
--------------------------------------------------------------------------
-- Date        Initials  Modification
--------------------------------------------------------------------------
-- 10/06/08    KC        Created
-- 10/09/08    KC        Removed DeliverableType as a Param.
--                       changed to use Fct table
-- 10/13/08    KC        Finalized @SubcontractSpecialist search
--                       and SubOut logic 
-- 11/12/08    KC        Added another DeliverableCat code
-- 11/13/08    KC        Added Security and new GroupBy Value (SC)
-- 11/20/08    KC        Added SponsorTypeName to ResultSet
-- 11/25/08    KC        Added two more Statuses
-- 12/01/08    KC        Added new REPORTCAT, REPORTCAT_44
-- 12/08/08    KC        Added @FundNumber and @PrincipalInvestigator
-- 12/09/08    KC        Added @OriginatingSponsor and @Sponsor
--                       DaysCalc also changed
-- 12/10/08    KC        Added WITH RECOMPILE, use TempTable now
-- 12/11/08    KC        Changes to Subcontractor, including parsing.
-- 12/17/08    KC        New Security function
-- 01/05/08    KC        Security Function Perf Issues: use TempTable
--                       & changed Dayscompleted data type
-- 01/07/09    KC        Increased size of Comments field in Temp table to 2000
--
-- =======================================================================
CREATE PROCEDURE dbo.RptSubContractOutActivityDetailReport
     (
     @StartDate                         DATETIME,  
     @EndDate                           DATETIME,
     @DeliverableStatus                 VARCHAR(100) = NULL,
     @Institution                       VARCHAR(100) = NULL,
     @Department                        VARCHAR(100) = NULL,
     @Unit                              VARCHAR(100) = NULL,
     @ChiefCode                         VARCHAR(4)   = NULL,
     @FundNumber                        VARCHAR(1000) = NULL,
     @PrincipalInvestigator             VARCHAR(100) = NULL, 
     @OriginatingSponsor                VARCHAR(100) = NULL,
     @Sponsor                           VARCHAR(100) = NULL,
     @Subcontractor                     VARCHAR(200) = NULL,
     @SubcontractSpecialist             VARCHAR(100) = NULL,
     @DomainUserId                      INT
     ) 
WITH RECOMPILE                                          
AS
BEGIN
     -- Initial Settings
     SET NOCOUNT ON
     
     -- Declare Local Variables
     DECLARE   @Error              INT,
               @RowCount           INT

     -- Need to break the filter out to multiple steps, so need a temp table here
     DECLARE   @Subcontracts TABLE (
                    FolderNumber             VARCHAR(12)    NULL,
                    InfoEdPropNumber         VARCHAR(50)    NULL,
                    Institution              VARCHAR(50)    NULL,
                    Department               VARCHAR(50)    NULL,
                    Unit                     VARCHAR(50)    NULL,
                    ChiefCode                VARCHAR(4)     NULL,
                    SponsorName              VARCHAR(75)    NULL,
                    SponsorTypeName          VARCHAR(50)    NULL,
                    SecondarySponsor         VARCHAR(75)    NULL,
                    ProposalShortTitle       VARCHAR(64)    NULL,
                    PrincipalInvestigator    VARCHAR(64)    NULL,
                    ProjectStartDate         DATETIME       NULL,
                    ProjectEndDate           DATETIME       NULL,
                    InstrumentType           VARCHAR(50)    NULL,
                    SubContractorName        VARCHAR(75)    NULL,
                    BudgetProjectStartDate   DATETIME       NULL,
                    BudgetProjectEndDate     DATETIME       NULL,
                    ProjectAwardedAmount     MONEY          NULL,
                    BudgetStartDate          DATETIME       NULL,
                    BudgetEndDate            DATETIME       NULL,
                    BudgetFundNumber         VARCHAR(20)    NULL,
                    ExpenseAmount            MONEY          NULL,
                    IndirectExpenses         MONEY          NULL,
                    DirectExpenses           MONEY          NULL,
                    CashBalance              MONEY          NULL,
                    ReportId                 BIGINT         NULL,
                    ReportName               VARCHAR(50)    NULL,
                    REPORTCAT                VARCHAR(80)    NULL,
                    REPORTSTAT               VARCHAR(80)    NULL,
                    SubmittedDate            DATETIME       NULL,
                    DueDate                  DATETIME       NULL,
                    StatusDate               DATETIME       NULL,
                    CompletedDate            DATETIME       NULL,
                    DaysFromDueToCompleted   VARCHAR(5)     NULL,
                    SubmittedBy              VARCHAR(50)    NULL,
                    StatusBy                 VARCHAR(50)    NULL,
                    CompletedBy              VARCHAR(50)    NULL,
                    PeriodStartDate          DATETIME       NULL,
                    PeriodEndDate            DATETIME       NULL,
                    DeliverableComments      VARCHAR(2000)  NULL,
                    REPORTCAT_CODE           VARCHAR(50)    NULL,
                    REPORTSTAT_CODE          VARCHAR(50)    NULL,
                    AgreementId              INT            NULL,
                    InstitutionId            INT            NULL,
                    DepartmentId             INT            NULL,
                    UnitId                   INT            NULL,
                    SponsorId                INT            NULL,
                    PrincipalInvestigatorId  INT            NULL,
                    SubcontractsYN           CHAR(1)        NULL,
                    SubContractorId          INT            NULL,
                    SubOutContractorId       INT            NULL )

     -- ALL checking
     IF @DeliverableStatus IN ('ALL','','0') SET @DeliverableStatus = NULL
     IF @Institution IN ('ALL','','0') SET @Institution = NULL
     IF @Department IN ('ALL','','0') SET @Department = NULL
     IF @Unit IN ('ALL','','0') SET @Unit = NULL
     IF @ChiefCode IN ('ALL','','0') SET @ChiefCode = NULL
     IF @FundNumber IN ('ALL','','0') SET @FundNumber = NULL
     IF @PrincipalInvestigator IN ('ALL','','0') SET @PrincipalInvestigator = NULL
     IF @OriginatingSponsor IN ('ALL','','0') SET @OriginatingSponsor = NULL
     IF @Sponsor IN ('ALL','','0') SET @Sponsor = NULL
     IF @Subcontractor IN ('ALL','','0') SET @Subcontractor = NULL
     IF @SubcontractSpecialist IN ('ALL','','0') SET @SubcontractSpecialist = NULL

     -- If drilling down to a single status, set the codes here
     IF @DeliverableStatus IS NOT NULL
          SELECT    @DeliverableStatus = CASE @DeliverableStatus
                                             WHEN 'UnExecutedAgreementRecd' THEN 'REPORTSTAT_41'
                                             WHEN 'PendingGA' THEN 'REPORTSTAT_28'
                                             WHEN 'PendingDocFromDeptPI' THEN 'REPORTSTAT_33'
                                             WHEN 'PendingDeptPIAppr' THEN 'REPORTSTAT_29'
                                             WHEN 'InQueue' THEN 'REPORTSTAT_25'
                                             WHEN 'Assigned' THEN 'REPORTSTAT_26'
                                             WHEN 'InNegotiation' THEN 'REPORTSTAT_27'
                                             WHEN 'PartiallyExecuted' THEN 'REPORTSTAT_30'
                                             WHEN 'FullyExecuted' THEN 'REPORTSTAT_31'
                                             WHEN 'OtherUnresolved' THEN 'REPORTSTAT_32'
                                             WHEN 'PendingOutYears' THEN 'REPORTSTAT_35'
                                             ELSE 'ERROR'
                                         END
                                             
     -- Check for Erroro
     IF @DeliverableStatus = 'ERROR'
     BEGIN
          RAISERROR ('ERROR! DeliverableStatus has an invalid value(%s). Set to a valid StatusColumn name.',11,1,@DeliverableStatus) 
          RETURN -1
     END
     
     -- Performance Issues, Get Secured AgreementIds into a temp table
     CREATE TABLE   #tt_Agreements  (AgreementId INT)
     
     INSERT    #tt_Agreements (AgreementId)
     SELECT    AgreementId
     FROM      dbo.fnGetSecurityAgreements(@DomainUserId) 
               
     -- Result Set into temp table
     INSERT    @Subcontracts
                    (FolderNumber,
                    InfoEdPropNumber,
                    Institution,
                    Department,
                    Unit,
                    ChiefCode,
                    SponsorName,
                    SponsorTypeName,
                    SecondarySponsor,
                    ProposalShortTitle,
                    PrincipalInvestigator,
                    ProjectStartDate,
                    ProjectEndDate,
                    InstrumentType,
                    SubContractorName,
                    BudgetProjectStartDate,
                    BudgetProjectEndDate,
                    ProjectAwardedAmount,
                    BudgetStartDate,
                    BudgetEndDate,
                    BudgetFundNumber,
                    ExpenseAmount,
                    IndirectExpenses,
                    DirectExpenses,
                    CashBalance,
                    ReportId,
                    ReportName,
                    REPORTCAT,
                    REPORTSTAT,
                    SubmittedDate,
                    DueDate,
                    StatusDate,
                    CompletedDate,
                    DaysFromDueToCompleted,
                    SubmittedBy,
                    StatusBy,
                    CompletedBy,
                    PeriodStartDate,
                    PeriodEndDate,
                    DeliverableComments,
                    REPORTCAT_CODE,
                    REPORTSTAT_CODE,
                    AgreementId,
                    InstitutionId,
                    DepartmentId,
                    UnitId,
                    SponsorId,
                    PrincipalInvestigatorId,
                    SubcontractsYN,
                    SubContractorId,
                    SubOutContractorId)
     SELECT    AI.FolderNumber,
               AI.InfoEdPropNumber,
               AI.Institution,
               AI.Department,
               AI.Unit,
               AI.ChiefCode,
               AI.SponsorName,
               AI.SponsorTypeName,
               AI.SecondarySponsor,
               AI.ProposalShortTitle,
               AI.PrincipalInvestigator,
               AI.ProjectStartDate,
               AI.ProjectEndDate,
               AI.InstrumentType,                                
               dbo.fnParseSubcontractorName(DEL.ReportName) AS SubContractorName,
               BUDG.ProjectStartDate AS BudgetProjectStartDate,
               BUDG.ProjectEndDate AS BudgetProjectEndDate,
               BUDG.ProjectAwardedAmount,
               BUDG.BudgetStartDate,
               BUDG.BudgetEndDate,
               BUDG.FundNumber AS BudgetFundNumber,
               BUDG.ExpenseAmount,
               BUDG.IndirectExpenses,
               BUDG.DirectExpenses,
               BUDG.CashBalance,
               DEL.ReportId,
               DEL.ReportName,
               DEL.REPORTCAT,
               DEL.REPORTSTAT,
               DEL.SubmittedDate,
               DEL.DueDate,
               DEL.ProcessedDate AS StatusDate,
               DEL.CompletedDate,
               DEL.DaysComplCalc AS DaysFromDueToCompleted,
               ISNULL(DEL.SubmittedBy,'UNASSIGNED') AS Submittedby,
               DEL.StatusBy,
               DEL.CompletedBy,
               DEL.PeriodStartDate,
               DEL.PeriodEndDate,
               DEL.Comments AS DeliverableComments,
               DEL.REPORTCAT_CODE,
               DEL.REPORTSTAT_CODE,
               AI.AgreementId,
               AI.InstitutionId,
               AI.DepartmentId,
               AI.UnitId,
               AI.SponsorId,
               AI.PrincipalInvestigatorId,
               AI.SubcontractsYN,
               AI.SubContractorId,
               NULL
               
     FROM      dbo.AgrAgreement_Info AI

               -- Security Issues: Not all Users can see all Agreements!
               INNER JOIN
                    #tt_Agreements AUTH ON AI.AgreementId = AUTH.AgreementId

               INNER JOIN
                    dbo.vwInfoEdSubContractDeliverables DEL ON AI.InfoEdPropNumber = DEL.prop_no AND
                         DEL.REPORTCAT_CODE IN ('REPORTCAT_14','REPORTCAT_39','REPORTCAT_44')     -- Sub Outs Only.
               
               LEFT OUTER JOIN
                    -- This function uses the Agreement_Fct table to get Budget and Project data
                    dbo.fnGetFactTableBudget(@StartDate, @EndDate) BUDG ON AI.AgreementId = BUDG.AgreementId
               
     WHERE     (DEL.ProcessedDate BETWEEN @StartDate AND @EndDate) AND
               
               (@DeliverableStatus IS NULL OR DEL.REPORTSTAT_CODE = @DeliverableStatus) AND
               
               (@Institution IS NULL OR AI.InstitutionId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Institution))) AND
               (@Department IS NULL OR AI.DepartmentId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Department))) AND
               (@Unit IS NULL OR AI.UnitId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria(@Unit))) AND
               (@ChiefCode IS NULL OR AI.ChiefCode IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@ChiefCode))) AND
     
               (@PrincipalInvestigator IS NULL OR AI.PrincipalInvestigatorId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria( @PrincipalInvestigator ))) AND

               (@Sponsor IS NULL OR AI.SponsorId IN (SELECT Criteria_ID FROM dbo.fnGetMultiCriteria( @Sponsor ))) 
               
     ORDER BY  AI.Institution,
               AI.Department,
               AI.Unit,
               AI.FolderNumber,
               DEL.ProcessedDate
     

     SELECT @Error=@@ERROR,@RowCount=@@ROWCOUNT
     
     DROP TABLE #tt_Agreements
     
     IF @Error!=0
     BEGIN
          RAISERROR ('ERROR! Getting Intial Agreement list into TempTable, @Subcontracts',11,1)
          RETURN -1
     END

     -- Return Result Set using additional params
     SELECT    FolderNumber,
               InfoEdPropNumber,
               Institution,
               Department,
               Unit,
               ChiefCode,
               SponsorName,
               SponsorTypeName,
               SecondarySponsor,
               ProposalShortTitle,
               PrincipalInvestigator,
               ProjectStartDate,
               ProjectEndDate,
               InstrumentType,
               SubContractorName,
               BudgetProjectStartDate,
               BudgetProjectEndDate,
               ProjectAwardedAmount,
               BudgetStartDate,
               BudgetEndDate,
               BudgetFundNumber,
               ExpenseAmount,
               IndirectExpenses,
               DirectExpenses,
               CashBalance,
               ReportId,
               ReportName,
               REPORTCAT,
               REPORTSTAT,
               SubmittedDate,
               DueDate,
               StatusDate,
               CompletedDate,
               DaysFromDueToCompleted,
               SubmittedBy,
               StatusBy,
               CompletedBy,
               PeriodStartDate,
               PeriodEndDate,
               DeliverableComments,
               REPORTCAT_CODE,
               REPORTSTAT_CODE,
               AgreementId,
               InstitutionId,
               DepartmentId,
               UnitId,
               SponsorId,
               PrincipalInvestigatorId,
               SubcontractsYN,
               SubContractorId,
               SubOutContractorId
     FROM      @Subcontracts
     WHERE     (@FundNumber IS NULL OR BudgetFundNumber IN (SELECT Code FROM dbo.fnGetMultiCriteriaCode(@FundNumber))) AND
               
               (@OriginatingSponsor IS NULL OR SecondarySponsor = @OriginatingSponsor ) AND

               -- If user is drilling down, this would be passed...
               (@Subcontractor IS NULL OR SubContractorName = @SubContractor) AND

               (@SubcontractSpecialist IS NULL OR SubmittedBy = @SubcontractSpecialist OR
               (@SubcontractSpecialist = 'UNASSIGNED' AND SubmittedBy IS NULL )) 
               
     SELECT @Error=@@ERROR,@RowCount=@@ROWCOUNT
     IF @Error!=0
     BEGIN
          RETURN -1
     END
     
     -- Return Success
     RETURN 0

     
END
go

IF OBJECT_ID('dbo.RptSubContractOutActivityDetailReport') IS NOT NULL
    PRINT '<<< CREATED PROCEDURE dbo.RptSubContractOutActivityDetailReport >>>'
ELSE
    PRINT '<<< FAILED CREATING PROCEDURE dbo.RptSubContractOutActivityDetailReport >>>'
go

GRANT EXECUTE ON dbo.RptSubContractOutActivityDetailReport TO InsightReport,Insight
go


